import json
from autotest import VAR

logger = VAR.logger


def getValueByPath(data, valuePath):
    """从json串中获取数据，通过value_path,类似于data.summary.total"""
    try:
        paths = valuePath.strip().split(".")
        res = data
        count = 0
        while count < len(paths):
            if res:
                res = res.get(paths[count])
            count += 1
        return res
    except Exception as e:
        logger.exception("getValueByPath,data--{},valuePath--{}".format(data, valuePath))


def setValueByPath(data, value, valuePath):
    """
    将data中的valuepath下的值设置为value
    :param data: 一个json串
    :param value: 要设置的值
    :param valuePath: 值路径 如data.applicant.idRiskList.p2p_bucket_short
    :return: 
    """
    l = valuePath.split(".")
    if len(l) == 4:
        a, b, c, d = l
        data[a][b][c][d] = value
    else:
        raise Exception("值路径不是4层的暂时不支持")


def beauty_json(jsonObj):
    return json.dumps(jsonObj, indent=4, ensure_ascii=False)
